package com.example.springboot.controller.redis;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/11/29 10:26
 */
@RestController
@RequestMapping("/czk")
@Api(tags = "点赞管理")
public class GiveAlikeController {
    private static final String GAVE_A_LIKE = "gave_a_like";

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 点赞
     *
     * @param postId
     * @return
     */
    @GetMapping("/like/{postId}/{userId}")
    @ApiOperation(value = "点赞")
    public String giveAlike(@PathVariable int postId, @PathVariable String userId) {
        // 拿到用户id
        System.out.println(userId);
        // 点赞
        String key = GAVE_A_LIKE + postId;
        Long result = redisTemplate.opsForSet().add(key, userId);
        if (result != null && result == 1L) {
            return "点赞成功";
        } else {
            return "重复点赞";
        }
    }

    /**
     * 取消点赞
     *
     * @param postId
     * @param userId
     * @return
     */
    @GetMapping("/remove/like/{postId}/{userId}")
    @ApiOperation(value = "取消点赞")
    public String undoLike(@PathVariable int postId, @PathVariable String userId) {
        String key = GAVE_A_LIKE + postId;
        Long result = redisTemplate.opsForSet().remove(key, userId);
        if (result != null && result == 1L) {
            return "取消成功";
        } else {
            return "重复取消点赞";
        }
    }

    /**
     * 点赞数与是否点赞
     *
     * @param postId
     * @param userId
     * @return
     */
    @GetMapping("/count/{postId}/{userId}")
    @ApiOperation(value = "点赞数与是否点赞")
    public Map<String, Object> getCountAndIsLike(@PathVariable int postId, @PathVariable String userId) {
        String key = GAVE_A_LIKE + postId;
        Map<String, Object> map = new HashMap<>();
        // 点赞数
        Long size = redisTemplate.opsForSet().size(key);
        // 是否点赞
        Boolean member = redisTemplate.opsForSet().isMember(key, userId);
        map.put("size", size);
        map.put("isLike", member);
        return map;
    }

    /**
     * 点赞详情
     *
     * @param postId
     * @return
     */
    @GetMapping("/like/all/{postId}")
    @ApiOperation(value = "点赞详情")
    public Set<String> likeAll(@PathVariable int postId) {
        String key = GAVE_A_LIKE + postId;
        Set<String> members = redisTemplate.opsForSet().members(key);
        return members;
    }
}
